const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const { vueTpl, serverTemplate } = require('./template')

const selectCreateType = (list) => ({
    name: 'type',
    type: 'list',
    message: '（必填）需要创建文件的项目:',
    choices: list,
    default: 0
});

const typeName = () => ({
    name: 'name',
    type: 'input',
    message: '（必填）请输入组件 name ，将用作目录及文件名:',
    validate: (value) => {
        if (value.trim() === '') {
            return '组件 name 是必填项!'
        }
        return true
    }
});

const typePath = () => ({
    name: 'path',
    type: 'input',
    message: '（必填）请输入新建接口路径:',
    validate: (value) => {
        if (value.trim() === '') {
            return '接口路径是必填项!'
        }
        return true
    }
});

async function create() {
    const packageList = fs.readdirSync("./packages");
    const { type } = await inquirer.prompt([selectCreateType(packageList)]);
    if (type?.includes('client')) {
        // 客户端在pages里面创建
        const { name } = await inquirer.prompt([typeName()]);
        const url = path.join(__dirname, `../packages/${type}/src/pages/${name}`);
        fs.mkdirSync(url);
        // 写入index文件
        fs.writeFileSync(`${url}/index.vue`, vueTpl(name), 'utf-8');
        fs.writeFileSync(`${url}/config.ts`, '', 'utf-8');
        fs.mkdirSync(`${url}/components`);
    } else if (type?.includes('server')) {
        // 服务端在interface里面创建
        const { name, path: inputPath } = await inquirer.prompt([typeName(), typePath()]);
        const url = path.join(__dirname, `../packages/${type}/interface/${name}.js`);
        fs.writeFileSync(url, serverTemplate(name, inputPath), 'utf-8')
    } else {
        // common
    }
};

module.exports = {
    create
}